package org.cc.media.player;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.amazon.webservices.awsecommerceservice._2013_08_01.AWSECommerceService;
import com.amazon.webservices.awsecommerceservice._2013_08_01.AWSECommerceServicePortType;
import com.amazon.webservices.awsecommerceservice._2013_08_01.Item;
import com.amazon.webservices.awsecommerceservice._2013_08_01.ItemSearch;
import com.amazon.webservices.awsecommerceservice._2013_08_01.ItemSearchRequest;
import com.amazon.webservices.awsecommerceservice._2013_08_01.ItemSearchResponse;
import com.amazon.webservices.awsecommerceservice._2013_08_01.Items;
import com.amfam.brokerage.test.AwsHandlerResolver;

public class ShoutcastMetadataPoller implements Runnable {

	private String url;
	private String songName = "";
	private Boolean pollMeta = true;
	
	String secretKey = "r4LUAMYaKV0Gz1aUDxHujxacTpQi7s/oe2z5TD1m";
	String awsKey = "AKIAJH6JDB3LQTTJXW4Q";	

	AWSECommerceServicePortType port;


	public ShoutcastMetadataPoller(String url) {
		this.url = url;
		AWSECommerceService service = new AWSECommerceService();
		service.setHandlerResolver(new AwsHandlerResolver(secretKey)); // important
		port = service.getAWSECommerceServicePort();
	}

	@Override
	public void run() {
		while (pollMeta) {
			try {
				Thread.sleep(5000);
				poll(url);
			} catch (InterruptedException e) {
				// do nothing.
			}
		}
	}

	//TODO Until I can figure out a better way (pull it from the stream),
	//     this will have to do.
	private void poll(String url) {
		if (url.contains("radionomy.net")) {
			return;
		}
		try {
			Document doc = Jsoup.connect(url + "/7.html")
					.userAgent("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36")
					.timeout(0).followRedirects(true).execute().parse();
			String body = doc.body().text();
			String[] data = body.split(",");
			if (data.length > 6) {
				if (!songName.equals(data[6])) {
					songName = data[6];
					GuiPlayer.getTrackTitle().setText(songName);
					String[] details = songName.split(" - ");
					System.out.println("Artist: " + "[" + details[0] + "]");
					System.out.println("Track: " + "[" + details[1] + "]");
					System.out.println("");
					GuiPlayer.getAlbumArt().setIcon(new ImageIcon(getAlbumArt(details[0], details[1])));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//TODO This needs to be un-hacked and optimized.
	private Image getAlbumArt(String artist, String title) {
		BufferedImage myPicture = null;
		try {
			myPicture = ImageIO.read(this.getClass().getResource("/desert.jpg"));
			ItemSearchResponse response = port.itemSearch(buildRequest(artist, title));
			String imageUrl = "";
			String buyLink = "";
			for (Items itemList : response.getItems()) {
				List<Item> items = itemList.getItem();
				for (Item item : items) {
					buyLink = item.getDetailPageURL();
					imageUrl = item.getMediumImage().getURL();
					break;
				}
			}

			if (!StringUtils.isEmpty(imageUrl)) {
				myPicture = ImageIO.read(new URL(imageUrl));
			}
			//TODO This should be moved out of this method.
			if (!StringUtils.isEmpty(buyLink)) {
				GuiPlayer.getBuyLink().setText("Buy this item!");
				GuiPlayer.getBuyLink().setName(buyLink);
				GuiPlayer.getBuyLink().setVisible(true);
			} else {
				GuiPlayer.getBuyLink().setText("");
				GuiPlayer.getBuyLink().setVisible(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return myPicture.getScaledInstance(200, -1, Image.SCALE_SMOOTH);

	}
	
	private ItemSearch buildRequest(String artist, String title) {
		ItemSearchRequest itemRequest = new ItemSearchRequest();
		itemRequest.setSearchIndex("Music");
		itemRequest.setArtist(artist);
		//itemRequest.setTitle(title);
		itemRequest.setKeywords(title);
		itemRequest.getResponseGroup().add("Large");
		ItemSearch itemElement = new ItemSearch();
		itemElement.setAWSAccessKeyId(awsKey);
		itemElement.setAssociateTag("whaddayaknow");
		itemElement.getRequest().add(itemRequest);
		return itemElement;
	}
	

	public Boolean getPollMeta() {
		return pollMeta;
	}

	public void setPollMeta(Boolean pollMeta) {
		this.pollMeta = pollMeta;
	}
}
